<script>
import parentChart from "./chart";
import color from "./config/color";
import grid from "./config/grid";
import legend from "./config/legend";
import pieSeries from "./config/pieSeries";
export default {
  name: "appPieChart",
  extends: parentChart,
  data() {
    return {};
  },
  methods: {
    /**
     * 父类 mounted方法 和 watch data 都自动进行调用
     * @param chart echart实例
     */
    createChart(chart) {
      if (!chart) return;
      // 判断数据
      this.emptyData = false;
      if (!this.data || !this.data.length) {
        return (this.emptyData = true);
      }
      const defaultOptions = {
        grid: grid,
        tooltip: {
          show: true
        },
        color: color
      };
      // 克隆
      let options = JSON.parse(JSON.stringify(defaultOptions));

      // 设置数据
      this.setSeries(options);
      // 设置legend
      this.setLegend(options);

      // 绘制chart (调用父类的render函数)
      this.render(options);
    },
    setSeries(options) {
      if (Array.isArray(this.data)) {
        const s = JSON.parse(JSON.stringify(pieSeries));
        s.data = this.data;
        options.series = [s];
      }
    },
    setLegend(options) {
      options.legend = JSON.parse(JSON.stringify(legend));
      let data = [];
      if (Array.isArray(this.data) && this.data.length) {
        data = this.data;
      }
      options.legend.orient = "vertical";
      // legend 显示的内容（）
      options.legend.formatter = name => {
        const item = this.data.find(d => d.name === name);
        if (item && item.desc) {
          return item.name + "：" + item.desc;
        } else {
          return name;
        }
      };
      options.legend.data = data;
    }
  }
};
</script>
